#!/bin/bash
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: yandi-upgrade-efi-system.sh
# author: david921518@qq.com

################
# global vars
################

# 1. get current system version
kpcos_release_file=/etc/kpcos-release
system=$(grep "NAME=" $kpcos_release_file | awk '{split($0,a,"="); print a[2]}')
version=$(grep "VERSION_ID=" $kpcos_release_file | awk '{split($0,a,"="); print a[2]}')
if [ "${system}" != "KPCOS-YanDi" ]; then
  echo "Unknown system [${system}]"
  exit 1
fi

populate_root ()
{
  WORK_DIR=$1
  echo "working dir=[${WORK_DIR}]"

  # 1. banner
  if [ -f "${WORK_DIR}/root/etc/banner" ]; then
    cp -f "${WORK_DIR}"/root/etc/banner /etc/banner
  fi

  # 2. init.d
  if [ -e "${WORK_DIR}/root/etc/init.d" ]; then
    cp -af "${WORK_DIR}"/root/etc/init.d/* /etc/init.d/
  fi

  # 3. rc2.d
  if [ -e "${WORK_DIR}/root/etc/rc2.d" ]; then
    cp -af "${WORK_DIR}"/root/etc/rc2.d/* /etc/rc2.d/
  fi

  # 4. rc3.d
  if [ -e "${WORK_DIR}/root/etc/rc3.d" ]; then
    cp -af "${WORK_DIR}"/root/etc/rc3.d/* /etc/rc3.d/
  fi

  # 5. rc4.d
  if [ -e "${WORK_DIR}/root/etc/rc4.d" ]; then
    cp -af "${WORK_DIR}"/root/etc/rc4.d/* /etc/rc4.d/
  fi

  # 6. rc5.d
  if [ -e "${WORK_DIR}/root/etc/rc5.d" ]; then
    cp -af "${WORK_DIR}"/root/etc/rc5.d/* /etc/rc5.d/
  fi

  # 7. systemd
  if [ -e "${WORK_DIR}/root/etc/systemd" ]; then
    cp -af "${WORK_DIR}"/root/etc/systemd/* /etc/systemd/
  fi

  # 8. /usr/sbin
  if [ -e "${WORK_DIR}/root/usr/sbin" ]; then
    cp -af "${WORK_DIR}"/root/usr/sbin/* /usr/sbin/
  fi
}

upgrade_from_0_5 ()
{
  echo "Upgrade from 0.5" 2>&1 | tee /dev/kmsg

  /usr/sbin/kpc-upgrade-all-pkgs.sh

  rm -rf ./upgrade*
  curl -o upgrade.tgz -L https://gitee.com/m8t/kpcos/raw/master/distro/yandi/releases/1.0/ports/amd64/upgrade.tgz
  chksum=$(md5sum upgrade.tgz | awk '{print $1}')
  echo "download upgrade.tgz md5sum is [${chksum}]" 2>&1 | tee /dev/kmsg
  if [ "${chksum}" != "50c10aed0f793a2d5de3fc547c8d2ca3" ]; then
    echo "upgrade.tgz is incorrect!" 2>&1 | tee /dev/kmsg
    exit 1
  fi
  tar -zvxf upgrade.tgz
  if [ -e ./upgrade ]; then
    populate_root ./upgrade
  fi
}

case "${version}" in
"0.5") echo "System is latest version [${version}]" 2>&1 | tee /dev/kmsg
  ;;

*) echo "Unsupported system version [${version}]" 2>&1 | tee /dev/kmsg
  ;;
esac

# restart system
#poweroff

